import { login, logout, getInfo } from '@/api/user'
import { getStorage, setStorage, removeStorage } from '@/utils/auth'
// import { resetRouter } from '@/router'
import { resetRouter, setRouterMenus } from '@/router/index'

const getDefaultState = () => {
	return {
		token: getStorage('Authorization'),
		name: '',
		avatar: '',
		info: getStorage('userInfo') ? JSON.parse(getStorage('userInfo')) : {},
		//menus: JSON.parse(localStorage.getItem('menus')),
		loadMenus: false,
		coin_name:'',//秀币名称
		//roles: getStorage('user-role') ? JSON.parse(getStorage('user-role')) : [],
	}
}

const state = getDefaultState()

const mutations = {
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState())
	},
	SET_TOKEN: (state, token) => {
		state.token = token
		setStorage('Authorization', token)
		setStorage('hasLogin', true)
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_INFO: (state, info) => {
		state.info = info
		setStorage('userInfo',info)
	},
	SET_MENUS: (state, menus) => {
		state.menus = menus
	},
	SET_MENU_LOAD: (state, status) => {
		state.loadMenus = status
	},
	SET_ROLE: (state, roles) => {
		setStorage('user-role', JSON.stringify(roles))
		state.roles = roles
	},
	COIN_NAME: (state, data) => {
		state.coin_name = data
	},
}
const actions = {
	// user login
	login ({ commit }, userInfo) {
		return new Promise((resolve, reject) => {
			login(userInfo).then(response => {	
				console.log("responseresponseresponse",response.info)
				commit('SET_TOKEN', response.agent_token)
				commit('SET_INFO', response.info)
				// commit('SET_MENUS', response.menu)
				// commit('SET_ROLE', response.roles)
				// setRouterMenus(response.menu);
				commit('SET_MENU_LOAD', true)
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// get user info
	getInfo ({ commit, state }) {
		return new Promise((resolve, reject) => {
			getInfo().then(response => {
				if (!response) {
					return reject('登录失效，请重试')
				}
				const  info = response
				commit('SET_INFO',info)
				// commit('SET_MENUS', menu)
				// commit('SET_ROLE', roles)
				// commit('SET_MENU_LOAD', true)
				// setRouterMenus(state.menus);
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// user logout
	logout ({ commit, state }) {
		return new Promise((resolve, reject) => {
			removeStorage('Authorization') // must remove  token  first
			removeStorage('hasLogin') // must remove  token  first
			removeStorage('userInfo') // must remove  token  first
			resetRouter()
			commit('RESET_STATE')
			location.reload()
		})
	},
	// remove token
	resetStorage ({ commit }) {
		return new Promise(resolve => {
			removeStorage() // must remove  token  first
			commit('RESET_STATE')
			resolve()
		})
	},
	coinName ({ commit,state },data) {
		commit('COIN_NAME',data)
	},
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}

